<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--@elvariable id="room" type="demo.pojo.room.Room"--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!doctype html>
<html>
<head>
    <title>发布房间信息</title>
</head>

<style>

    /*滑动组件*/
    #details_page_wrapper {
        overflow: hidden;
        background-color: white;
    }

</style>


<style>

    .room_reserve_input {
        margin-left: 5%;
        position: absolute;
        width: 60%;
        height: 30px;
        border: 0px;
        padding-left: 20px;
        font: 400 13.3333px Arial;
    }

    .room_reserve_label {
        width: 30%;
        font-size: large;
        color: #7a7a7a;
        margin-left: 5%;
    }

</style>


<script>
    loadcss('css/zufang.css');
</script>

<body>


<!--列表-->
<div style="position: relative">


    <div id="details_page_wrapper">

        <ul id="details_page__scroller">
            <li class="page-house-container" id="swipe">

                <div class="slide" id="mySwipe" style="visibility: visible;   height: 50%;">


                    <%--图片采用轮播且懒加载--%>
                    <ul class="slide__wrapper" id="fimg" data-appsource="200100000004"
                        style="width: 100%; height: 100% ">

                        <c:choose>
                            <c:when test="${room.images.size()>0}">
                                <c:forEach items="${room.images}" var="img">
                                    <li class="slide__item">
                                        <a href="/resource/preview/2/${img}.jpg" target="_blank">
                                            <img alt="${room.location.address}"
                                                 src="/resource/preview/2/${img}.jpg">
                                        </a>
                                    </li>
                                </c:forEach>
                            </c:when>
                            <c:otherwise>
                                <li class="slide__item">
                                    <img alt="${room.location.address}"
                                         src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1546502159888&di=ba8195972eb78359422bb19a4e6b59d1&imgtype=0&src=http%3A%2F%2Fp2.so.qhimgs1.com%2Ft01481b7750ea1d245e.png">
                                </li>
                            </c:otherwise>
                        </c:choose>

                    </ul>

                </div>

                <div id="room_details_mesage_panel">


                    <!-- 房源标题 -->
                    <div class="box page-title-info">
                        <h2 class="page-title-h2">${room.name}</h2>
                    </div>

                    <div class="box page-house-cost page-cost-decentralized">

                        <h4 class="page-title-h3">
                            价格
                        </h4>
                        <div class="box content__detail--info">
                            <ul>
                                <c:forEach items="${room.prices}" var="p">
                                    <li>
                                        <span>价格${p.serial}</span>
                                        <span>${p.text}</span>
                                    </li>
                                </c:forEach>
                            </ul>
                        </div>

                    </div>


                    <div class="box page-house-cost page-cost-decentralized">

                        <h4 class="page-title-h3">
                            地址
                        </h4>
                        <span style="margin-left: 20px">
                            ${room.location.address}
                        </span>
                        <span style="margin-right: 10px">
                            ${room.location.detailedDescription}
                        </span>
                    </div>


                    <div class="box page-house-cost page-cost-decentralized">

                        <h4 class="page-title-h3">
                            简介
                        </h4>
                        <span style="margin-left: 20px">
                            ${room.description}
                        </span>
                    </div>


                    <div class="box page-house-cost page-cost-decentralized">

                        <h4 class="page-title-h3">
                            评价
                        </h4>
                        <ul id="evalutations-ul">


                        </ul>
                    </div>
                </div>


                <form id="room_reserve_form"
                      style="display: none;background-color: #edecee;height: 100%;padding-top: 5%">
                    <div style="height: 35px">

                        <label class="room_reserve_label" for="room_reserve_unit">
                            租用方式:
                        </label>
                        <select onblur="window.scroll(0,0)" class="room_reserve_input" id="room_reserve_unit"
                                name="serial"
                                oninput="refreshSum()">
                            <c:forEach items="${room.prices}" var="price">
                                <option value="${price.serial}">${price.text}

                                    <c:if test="${price.deposit!=0}">


                                        <fmt:formatNumber type="number" var="pint" value="${price.deposit}"
                                                          maxFractionDigits="0"/>

                                        (含押金:
                                        <c:choose>
                                            <c:when test="${price.deposit-pint==0.0}">
                                                ${pint}
                                            </c:when>
                                            <c:otherwise>
                                                ${price.deposit}
                                            </c:otherwise>
                                        </c:choose>

                                        元)

                                    </c:if>

                                </option>
                            </c:forEach>
                        </select>

                    </div>

                    <div style="height: 30px">
                        <label class="room_reserve_label" for="room_reserve_num">
                            租用数量:
                        </label>
                        <input style="padding-left: 20px" onblur="window.scroll(0,0)" oninput="refreshSum()"
                               class="room_reserve_input"
                               id="room_reserve_num" type="number"
                               name="count" value="1">
                    </div>


                    <input type="hidden" name="roomId" value="${room.id}">

                    <div style="height: 30px;margin-top: 30px">

                        <label class="room_reserve_label" style="font-size: 20px">
                            合计:
                        </label>
                        <span style="margin-left: 15%;text-align: center;font-size: 15px"><b
                                id="room_reserve_sum">0.0</b>元</span>
                    </div>

                </form>

            </li>


        </ul>


        <div id="room_details_btn_group" class="fixed-bottom-btn-container">
            <div class="fixed-bottom-btn-box">
                <ul>
                    <li class="fixed--aside">
                        <div class="favorite-box" style="display: block;">
                        </div>
                    </li>
                    <li class="fixed--button">
                        <span class="green-small-btn" id="view_point">查看地图</span>
                        <span class="blue-small-btn" id="room_reserve_btn">立即预定</span>
                    </li>
                </ul>
            </div>
        </div>

        <%--预定按钮组--%>
        <div id="room_reserve_btn_group" class="fixed-bottom-btn-container" style="display: none;">
            <div class="fixed-bottom-btn-box">
                <ul>
                    <li class="fixed--button">
                        <span class="red-small-btn" id="room_reserve_cancel_btn">取消</span>
                        <span class="blue-small-btn" id="room_reserve_submit_btn" onclick="submit()">提交订单</span>
                    </li>
                </ul>
            </div>
        </div>


    </div>


</div>


<script>

    let prices = [];

    <c:forEach items="${room.prices}" var="p">

    prices[${p.serial}] = {};

    prices[${p.serial}].price =${p.price};

    prices[${p.serial}].deposit =${p.deposit};


    </c:forEach>


    function refreshSum() {

        //刷新价格

        let u = $('#room_reserve_unit').val();

        let num = $('#room_reserve_num');

        let n = num.val();

        if (n > 9999) {
            num.val(9999);
            n = 9999;
        }

        let sum = 0;


        if (n > 0) {
            sum = prices[u].price * n + prices[u].deposit;
        }


        $('#room_reserve_sum').text(sum);

    }

    refreshSum();

    let fb = $('.favorite-box');

    let id = "${room.id}";

    let state;

    //首先判断该房源有没有被当前房客收藏
    $.post('/room/isFavorite', {id: id}, function (fv) {

        state = fv;
        if (fv) {
            fb.append('<i></i>已收藏');
            fb.addClass('clicked');
        } else {
            fb.append('<i></i>收藏');
        }
    });

    //点击收藏按钮

    fb.click(function () {

        $.post('/room/favorite', {id: '${room.id}', state: !state}, function (fv) {//fv为变化后的状态

            state = fv;
            fb.empty();
            if (fv) {
                $('.favorite-box').addClass('clicked');

                Event.fanout('append_favoriteRoom', '${room.id}');

                fb.append('<i></i>已收藏');
            } else {
                $('.favorite-box').removeClass('clicked');

                Event.fanout('remove_favoriteRoom', '${room.id}');

                fb.append('<i></i>收藏');
            }

        });


    });

    //查看地图事件
    $('#view_point').click(function () {

        Backs.push(function () {

            //发起查看地图事件
            Event.fanout('view_point', {
                lat: ${room.location.latitude},
                lon: ${room.location.longitude}
            });

            //隐藏当前窗口
            dynamicPage.close();

        }, function () {

            //显示当前窗口
            dynamicPage.show();

            //广播点查看事件的补偿事件
            Event.fanout('compensation_view_point');

        });
    });


    new TouchSlider({id: 'mySwipe', speed: 600});


    let sp = $('#details_page_wrapper');
    var winHeight = $(window).height();   //获取当前页面高度


    sp.height(winHeight - 50 - 66);


    let is = new IScroll('#details_page_wrapper', {
        scrollbars: false,
        mouseWheel: false,
        interactiveScrollbars: false,
        shrinkScrollbars: 'scale',
        fadeScrollbars: false,
        scrollY: true,
        probeType: 1,
        bindToWrapper: true,
        click: true,
    });


    let ul = $('#evalutations-ul');

    function append_evaluation(evaluation) {

        //追加评价信息

        ul.append(' <li class="box" style="margin-bottom: 20px;">' +
            '                            <div>' +
            '                            <h6><b style="margin-left: 10px">' + evaluation.encryptValuer + ' :</b>  <i style="margin-left: 15px;margin-right: 5px">服务</i> ' + evaluation.service + '<svg t="1551495419888" class="icon" style="height: 10px;width: 10px" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1253" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M509.956458 125.700887l126.648468 241.487983 257.600963 52.040237L714.888873 620.511389l32.546254 273.694499-237.478669-117.137861-237.491972 117.137861 32.558533-273.694499L125.700887 419.229107l257.600963-52.040237L509.956458 125.700887" p-id="1254"></path></svg>' +
            '                                <i style="margin-left: 10px;margin-right: 5px">环境</i> ' + evaluation.environment + '<svg t="1551495419888" class="icon" style="height: 10px;width: 10px" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1253" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M509.956458 125.700887l126.648468 241.487983 257.600963 52.040237L714.888873 620.511389l32.546254 273.694499-237.478669-117.137861-237.491972 117.137861 32.558533-273.694499L125.700887 419.229107l257.600963-52.040237L509.956458 125.700887" p-id="1254"></path></svg>' +
            '                            </h6>' +
            '                                <div style="margin-left: 30px;margin-top: 10px;line-height: 15px">' +
            evaluation.evaluation +
            '                                </div>' +
            '                            </div>' +
            '                        </li>');

        is.refresh();

    }

    let evaluation_page = 0;

    function get_evaluations() {

        $.get('/room/evaluations', {id: '${room.id}', page: evaluation_page}, function (es) {

            evaluation_page++;

            for (let i in es) {
                append_evaluation(es[i]);
            }


            //已经没有更多评论了
            if (es.length === 0) {
                evaluation_page = -1;
            }

        });

    }

    get_evaluations();


    is.on('scrollEnd', function () {

        //如果已经到达顶端
        if (is.maxScrollY === is.y) {

            if (evaluation_page !== -1) {
                get_evaluations();
            }

        }


    });

    //手机端无法滑动问题.
    document.addEventListener('touchmove', function (e) {
        e.preventDefault();
    }, {
        capture: true,
        passive: false
    });

    is.refresh();

    //点击预定按钮

    let they;

    $('#room_reserve_btn').click(function () {

        $('#room_details_mesage_panel').hide();
        $('#room_reserve_form').show();

        $('#room_details_btn_group').hide();
        $('#room_reserve_btn_group').show();

        they = is.y;

        is.refresh();
        is.scrollTo(0, 0, 500);

    });


    $('#room_reserve_cancel_btn').click(function () {


        $('#room_details_mesage_panel').show();
        $('#room_reserve_form').hide();

        $('#room_details_btn_group').show();
        $('#room_reserve_btn_group').hide();

        is.refresh();
        is.scrollTo(0, they, 800);

    });


</script>


<script>


    function submit() {

        //序列化表单数据
        let formData = $('#room_reserve_form').serialize();

        let rid;


        function checkPay() {
            //监听关闭弹窗事件
            Event.on('dialog_close', function (data) {
                if (data.type === 'order_payment') {

                    if (rid) {

                        $.post('/order/pay/hasPaid', {id: rid}, function (b) {//返回订单是否成功付款

                            if (b) {
                                Event.fanout('append_payedOder', rid);
                            }
                            else {
                                Event.fanout('append_nonpaymentOrder', rid);
                            }

                        });

                        //销毁rid,保证时间的排他性
                        rid = false;

                    }
                }
            }, true);


            //监听'我已完成支付按钮'
            Event.on('i_have_payed', function () {

                if (rid) {

                    $.post('/order/pay/hasPaid', {id: rid}, function (b) {//返回订单是否成功付款


                        if (b) {

                            Event.fanout('append_payedOder', rid);

                            mydialog.display('html/dialog/completepayment.html');
                        }
                        else {
                            Event.fanout('append_nonpaymentOrder', rid);
                            alert('未查询到支付状态,请稍后刷新重试');
                        }

                    });

                    rid = false;
                }

            }, true);


            //显示支付确认面板
            Backs.push(function () {
                mydialog.display('html/dialog/payment.html', 'order_payment');
            }, function () {

                if (mydialog.isShow) {
                    mydialog.close();
                }
                else {
                    return true;    //事件已经失效
                }

            }, true);


            function wo() {
                Event.on('__windows.onfocus', function () {//手动检查
                    if (rid) {

                        $.post('/order/pay/hasPaid', {id: rid}, function (b) {
                            if (b) {

                                //关闭支付面板
                                mydialog.close();
                                Event.fanout('append_payedOder', rid);

                                alert('支付完成,可以在订单管理中查看您的订单');

                                //销毁id
                                rid = false;

                            } else {
                                wo();//递归
                            }
                        });

                    }
                }, true);//监听一次
            }

            wo();
        }


        //由于在post请求后打开新页面会被拦截,所以这里采用轮询的方式获取id,然后在新页面中打开

        //采用轮询法每隔0.3s查看一次,如果已经生成了rid就开启新页面.
        // 如果超过1.5秒生成了rid,但是没有跳转到新页面(说明被拦截),弹出一个手动访问的弹窗
        //如果没有生成rid,说明失败

        let to;
        let inl;

        to = setTimeout(function () {

            clearInterval(inl);

            if (!rid) {
                mydialog.close();
                alert('服务器没有发回响应,请稍后再试');
            }

        }, 1500);

        //每隔0.3s轮询一次,查看是否已经生成了rid,如果生成了rid则进行跳转.

        inl = setInterval(function () {
            if (rid) {
                clearTimeout(to);
                clearInterval(inl);

                //在这里打开支付页面可能会被浏览器当做弹窗给拦截
                window.open('/tenant/payment?orderId=' + rid, '_blank');

                //进行0.8s的判断,如果当前窗口仍然具有焦点.那么弹出一个手动打开支付页面的弹窗

                let to1;

                //window 在失焦时可能会清除一个空的to1,用flag2确保在弹窗没有被拦截失去焦点时不会弹出"去支付"面板
                let flag2 = true;

                window.onblur = function () {

                    //同时也令onblur事件失效
                    if (flag2) {

                        flag2 = false;

                        checkPay();

                        clearTimeout(to1);

                    }
                };

                to1 = setTimeout(function () {

                    if (flag2) {

                        /*  Event.on('goto-payment.press', function () {
  //                            checkPay();
                          }, true);*/

                        mydialog.dynamic('/tenant/goto-payment.html?orderId=' + rid);

                    }
                }, 800);


            }
        }, 300);

        //提交订单,提交的订单会产生一个订单id
        $.post('/order/tenant/reserve?' + formData, function (id) {

            rid = id;

        }).error(function (err) {
            console.log(err);
        });


    }


</script>


</body>
</html>